/*
 * 产品页面视图
 * @Author: ljb
 * @Date: 2018-03-27 17:52:07
 * @Last Modified by: ljb
 * @Last Modified time: 2019-04-16 09:03:56
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
    .v-customer-product-views {
        padding: 20px;
	}

	@deep: ~">>>";
	@{deep} .ivu-modal {
		top: 20px;
	}
	@{deep} .ivu-modal-body{
		min-height: 950px;
	}
</style>

<template>

	<div class="v-customer-product-views">

		<Tabs
			v-model="tag_name"
			type="card"
			@on-click="changeTab">

			<TabPane
				:label="$t('common.create')"
				name="新增">

				<product-create
					ref="create"
					:product-tags="product_tags"
					:positions="body_positions"
					:brands="brands"
					:group-brands="group_brands"
					:outer-chain="outer_chain"
					:categories="categories"
					:group-categories="group_categories"
					:cosmetic-materials="cosmetic_materials"
					:models-group="model_xmls"
					:loading="button_loading"
					:refresh="refreshCreateInfo"
					@post="postData"
					@syncSale="syncSale"
					@syncInventory="syncInventory"/>

			</TabPane>

			<TabPane
				:label="$t('product.customer_product')"
				name="查看">

				<!-- 搜索组件 -->
				<search-form
					:brands="brands"
					:group-categories="group_categories"
					@search="confirmSearch"
					@export="confirmExcel"/>

				<product-index
					:loading="table_loading"
					:brands="brands"
					:group-brands="group_brands"
					:brands-list="brandsList"
					:categories="categories"
					:group-categories="group_categories"
					:cosmetic-materials="cosmetic_materials"
					:sexes="sexes"
					:positions="body_positions"
					:products="products.data"
					@change-state="handleStateChange"
					@edit="productDetail"
					@delete="deleteProduct"
					@sort="confirmSearch"/>

				<br>

				<!-- 分页组件 -->
				<Row
					type="flex"
					justify="center">
					<Page
						:total="products.total"
						:current="products.current_page"
						:page-size="query_info.per_page"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>
				</Row>
			</TabPane>

			<TabPane
				v-if="getProviderType !== 1"
				:label="$t('store.store_products')"
				name="store-products">
				<storeProducts ref="store-products" />
			</TabPane>

		</Tabs>

		<Modal
			v-model="show_modal"
			:title="$t('product.update_product')">

			<!-- 产品编辑组件 -->
			<product-edit
				v-if="show_modal"
				ref="edit"
				:refresh="refreshCreateInfo"
				:product-tags="product_tags"
				:brands="brands"
				:group-brands="group_brands"
				:outer-chain="outer_chain"
				:categories="categories"
				:group-categories="group_categories"
				:cosmetic-materials="cosmetic_materials"
				:product-detail="product_detail"
				:models-group="model_xmls"
				:show-modal="show_modal"
				:loading="button_loading"
				:positions="body_positions"
				@update="updateProduct"/>

			<div slot="footer"/>

		</Modal>

	</div>

</template>

<script>

import qs from 'qs';
import { mapMutations, mapGetters } from 'vuex';
import API_LIST from 'src/API_LIST';
import { deleteEmptyValue } from 'src/utils/utils';
import { $t } from 'src/i18n/index';
import productCreate from './create';
import productIndex from './index';
import productEdit from './edit';
import searchForm from './search-form';
import detailModal from './taobao-detail';
import storeProducts from './store-products/views';

export default {

	name: 'ProductViews',

	components: {
		productCreate,

		productIndex,

		productEdit,

		searchForm,

		detailModal,

		storeProducts,
	},
	data() {
		return {
			query_info: {
				page: 1,

				per_page: 20,

				is_sale: '',

				is_deleted: '',

				is_hot: '',

				is_new: '',

				has_youzan: '',

				category_id: '',

				brand_id: '',

				keyword: '',

				sort_column: '',

				sort_by: '',
			},

			search_info: {
				page: 1,

				per_page: 20,
			}, // 分页信息

			tag_name: '新增',

			show_taobao_detail: false, // 淘宝详情按钮显示

			show_taobao_modal: false, // 淘宝详情弹框

			table_loading: false, // 表格更新时的loading

			show_modal: false, // 弹框的控制

			outer_chain: [], // 外链的类型

			product_detail: {}, // 产品详情

			products: {}, // 产品列表

			brands: {}, // 产品品牌

			product_tags: {}, // 产品的标签

			model_xmls: [], // 产品模型

			taobao_item: {}, // 淘宝商品详情

			button_loading: false, // 按钮的loading

			body_positions: [], // 身体部位

			sexes: [], // 性别选项

			categories: [], // 产品种类

			group_categories: [], // 产品种类成组

			cosmetic_materials: [], // 材质信息

			group_brands: [], // 系列信息

			brandsList: [], // 系列列表信息
		};
	},

	computed: {

		...mapGetters('userToken', [
			'getToken',
			'getProviderType',
		]),

		getTaobaoItem() {
			return this.taobao_item;
		},

	},
	mounted() {
		if (this.$route.query.watch) {
			this.tag_name = '查看';
			this.changeTab('查看');
		}

		this.fetchProductCreateInfo();
		// this.listenVisibilityChange();
	},
	methods: {

		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		/**
		 * 处理刷新事件
		 */
		refreshCreateInfo() {
			this.brands = {};
			this.cosmetic_materials = [];
			this.group_brands = [];
			this.model_xmls = [];
			return this.fetchProductCreateInfo();
		},

		/**
		 * 导出excel表格
		 * @return {undefined}
		 */
		confirmExcel(query_params) {
			const param = Object.assign({}, query_params, { token: this.getToken });
			window.open(`${API_LIST.CUST_EXPORT_EXCEL}?${qs.stringify(param)}`);
		},

		/**
         * 切换tab
         * @param  {string} tab_name {tab的name}
         * @return {undefined}
         */
		changeTab(tab_name) {
			if (tab_name === '查看') {
				this.fetchProductList(this.query_info);

				this.$refs.create.handleReset('formValidate');

				this.taobao_item = {};
			} else if (tab_name === 'store-products') {
				this.$refs['store-products'].fetchProducts();
			} else {
				this.products.data = [];

				this.taobao_item = {};

				this.show_taobao_detail = false;
			}
		},

		/**
         * 页码改变
         * @param  {string} pageNumber {当前页码}
         * @return {undefined}
         */
		pageChange(pageNumber) {
			this.search_info.page = pageNumber;

			this.search_info.per_page = this.query_info.per_page;

			this.fetchProductList(this.search_info);
		},

		/**
         * 每页显示数改变
         * @param  {string} per_page {当前每页显示数}
         * @return {undefined}
         */
		perPageChange(per_page) {
			this.search_info.per_page = per_page;

			this.query_info.per_page = per_page;

			this.fetchProductList(this.query_info);
		},

		/**
         * 确认搜索
         * @param  {Object} param {搜索的参数对象}
         * @return {undefined}
         */
		confirmSearch({
			is_sale, is_deleted, is_hot, is_new, has_youzan, brand_id, category_id, keyword, sort_column, sort_by,
		}) {
			this.query_info.is_sale = is_sale || '';

			this.query_info.is_deleted = is_deleted || '';

			this.query_info.is_hot = is_hot || '';

			this.query_info.is_new = is_new || '';

			this.query_info.has_youzan = has_youzan || '';

			this.query_info.brand_id = brand_id || '';

			this.query_info.category_id = category_id || '';

			this.query_info.keyword = keyword || '';

			this.query_info.sort_column = sort_column || '';

			this.query_info.sort_by = sort_by || '';

			this.search_info = JSON.parse(JSON.stringify(this.query_info));

			this.fetchProductList(this.query_info);
		},

		/**
		 * 同步有赞在售商品
		 * @return {undefined}
		 */
		syncSale() {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.CUST_YOUZAN_SYNC_SALE)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.sync_success'));
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})
				.finally(this.closeSpin);
		},

		/**
		 * 同步有赞仓库商品
		 * @return {undefined}
		 */
		syncInventory() {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.CUST_YOUZAN_SYNC_INVEN)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.sync_success'));
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})
				.finally(this.closeSpin);
		},

		/**
		 * 更新状态
		 * @param  {Object} param {更新状态需要的参数}
		 * @return {undefined}
		 */
		updateStatus(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.patch(API_LIST.CUSTOMER_PRODUCT_STATUS, param)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.update_success'));

					this.taobao_item = {};

					this.product_detail[param.type] = param.value;

					this.product_detail = null;
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})
				.finally(this.closeSpin);
		},

		/**
         * 新增产品的post数据
		 * @param {Object} param {新增参数对象}
         * @return {undefined}
         */
		postData(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.CUST_PRODUCT, param)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.create_success'));

					this.taobao_item = {};

					this.$refs.create.handleReset('formValidate');
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})

				.then(this.closeSpin);
		},

		/**
         * 查看产品详情
         * @param  {string} id {商品详情id}
         * @return {undefined}
         */
		productDetail(detail) {
			this.product_detail = detail;
			this.show_modal = true;
		},

		/**
         * 更新产品信息
		 * @param {String} id {产品id}
         * @param  {Object} param {需要更新的参数对象}
         * @return {undefined}
         */
		updateProduct(id, param) {
			this.showSpin();

			this.$http.post(`${API_LIST.CUST_PRODUCT}/${id}`, param)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.update_success'));

					this.show_modal = false;

					this.fetchProductList(this.search_info);
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(this.closeSpin);
		},

		/**
         * 删除产品
         * @param  {string} id {需要删除的产品的id}
         * @return {undefined}
         */
		deleteProduct(id) {
			this.$Modal.confirm({

				title: this.$t('product.tip'), // '温馨提示',
				content: this.$t('product.is_delete'), // '删除之后将无法恢复，确定吗？',

				onOk: () => {
					const param = {
						_method: 'DELETE',
					};

					this.table_loading = true;

					this.$http.post(`${API_LIST.CUST_PRODUCT}/${id}`, param)

						.then(({ data }) => {
							if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

							this.fetchProductList(this.search_info);

							this.$Message.success(this.$t('common.delete_success'));
						})

						.catch((err) => {
							this.$Message.error(err.message || err.statusText);
						})

						.then(() => { this.table_loading = false; });
				},
				onCancel: () => {},

			});
		},

		/**
         * 获取创建产品时所需信息
         * @return {undefined}
         */
		fetchProductCreateInfo() {
			this.showSpin($t('common.please_wait'));

			return this.$http.get(`${API_LIST.CUST_PRODUCT}/create`)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.outer_chain = data.product_url_types;

					this.brands = data.brands;

					this.group_brands = data.brand_with_series;

					this.product_tags = data.product_tags;

					this.model_xmls = data.assets_group;

					this.body_positions = data.body_positions;

					this.categories = data.categories;

					this.group_categories = data.group_categories;

					this.cosmetic_materials = data.cosmetic_materials;

					this.sexes = data.sexes;

					this.brandSeries(data.brand_with_series);
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(this.closeSpin);
		},

		/**
		 * 品牌列表的处理
		 * @param  {Array} groupBrands {品牌数据组}
		 * @return {undefined}
		 */
		brandSeries(groupBrands) {
			for (let i = 0; i < groupBrands.length; i += 1) {
				for (let k = 0; k < groupBrands[i].brand_series.length; k += 1) {
					this.brandsList.push(groupBrands[i].brand_series[k]);
				}
			}
		},

		/**
         * 获取产品列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchProductList(param) {
			this.table_loading = true;

			const query_str = qs.stringify(deleteEmptyValue(param));

			this.$http.get(`${API_LIST.CUST_PRODUCT}?${query_str}`)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.products = data.products;
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(() => { this.table_loading = false; });
		},

		/**
		 * 处理商品状体改变
		 * @param {object} row 商品详情
		 * @param {object} params 表单参数
		 * @return {undefined}
		 */
		handleStateChange({ row, ...params }) {
			this.product_detail = row;
			this.updateStatus(params);
		},

	},
};
</script>
